package priv.dajie.tzzq.bot.base;

import org.apache.http.Header;
import org.apache.http.client.CookieStore;
import org.apache.http.cookie.Cookie;
import org.apache.http.message.BasicHeader;
import priv.dajie.tzzq.Base;

import java.io.*;
import java.util.List;

public class BaseBot extends Base {

    private String cookiesName;
    protected String userName;
    protected String password;
    private Thread thread = null;

    public String getUserName() {
        return userName;
    }

    public String getPassword() {
        return password;
    }

    public BaseBot() {

    }

    public BaseBot(String userName, String password, String cookiesName) {
        this.userName = userName;
        this.password = password;
        this.cookiesName = System.getProperty("user.dir")+ "/cookies/" + cookiesName;
    }


    public void saveCookies() {
        File f = new File(System.getProperty("user.dir")+ "/cookies");
        if (!f.exists()) {
            f.mkdir();
        }
        ObjectOutputStream oos = null;
        try {
            oos = new ObjectOutputStream(new FileOutputStream(new File(cookiesName)));
            oos.writeObject(cookieStore);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    public boolean loadCookie() {
        return loadCookie(cookiesName);
    }

    public boolean loadCookie(String cookiesFileName) {
        File f = new File(cookiesFileName);
        if (f.exists()) {
            try {
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(cookiesFileName)));
                CookieStore cookieStoreTemp = (CookieStore) ois.readObject();
                for (Cookie cookie : cookieStoreTemp.getCookies()) {
                    cookieStore.addCookie(cookie);
                }
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
                return false;
            }
            return true;
        }
        System.out.println("加载cookies失败");
        return false;
    }

    public List<Cookie> getAllCookies() {
        return cookieStore.getCookies();
    }

    public Header getHeaderCookies(){ //获取字符串cookies
        StringBuilder cookiesStr = new StringBuilder();
        for(Cookie cookie : getAllCookies()){
            cookiesStr.append(cookie.getName()).append("=").append(cookie.getValue()).append("; ");
        }
        return new BasicHeader("Cookie", cookiesStr.toString());
    }

    public String getCookiesByName(String name) {
        List<Cookie> cookies = getAllCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(name)) {
                return cookie.getValue();
            }
        }
        return null;
    }

}
